package com.jphoebe.plugin.mybatis.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class FastJsonUtil {

	public FastJsonUtil() {
		// TODO Auto-generated constructor stub
	}

	public static String createJsonString(Object object) {
		// 禁用循环引用检测
		String jsonString = JSON.toJSONString(object, SerializerFeature.DisableCircularReferenceDetect);
		return jsonString;
	}

	/**
	 * 将对象的大写转换为下划线加小写，例如：userName-->user_name
	 *
	 * @param object
	 * @return
	 * @throws JsonProcessingException
	 */
     public static String createUnderlineJSONString(Object object) throws JsonProcessingException {
		ObjectMapper mapper = new ObjectMapper();
		mapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
		mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
		String reqJson = mapper.writeValueAsString(object);
		return reqJson;
	}
	/**
	* 将下划线转换为驼峰的形式，例如：user_name-->userName
	*
	* @param json
	* @param clazz
	* @return
	* @throws IOException
	*/
	public static <T> T toSnakeBean(String json, Class<T> clazz) throws IOException {
		ObjectMapper mapper = new ObjectMapper();
		mapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
		T reqJson =  mapper.readValue(json, clazz);
		return reqJson;
	}

	public static String createJsonSreingByErrorCode(Class cls, Object object){
		return  FastJsonUtil.createJsonStringByEnum(cls,object);
	}

	public static String createJsonStringByEnum(Class cls,Object object) {
		SerializeConfig config = new SerializeConfig();
		config.configEnumAsJavaBean(cls);
		String s = JSON.toJSONString(object, config);
		return s;
	}

	public static <T> T toBean(String jsonString, Class<T> cls) {
		T t = JSON.parseObject(jsonString, cls);
		return t;
	}

	public static <T> List<T> toBeanForList(String jsonString,
											Class<T> cls) {
		List<T> list = null;
		list = JSON.parseArray(jsonString, cls);
		return list;
	}

	/**
	 * @param jsonString
	 * @return
	 */
	public static List<Map<String, Object>> toBeanForListMap(
			String jsonString) {
		List<Map<String, Object>> list = JSON.parseObject(jsonString,
				new TypeReference<List<Map<String, Object>>>() {
				});
		return list;
	}
	public static HashMap<String, String> toBeanForHashMap(
			String jsonString) {
		HashMap<String, String> map = JSON.parseObject(jsonString,
				new TypeReference<HashMap<String, String>>() {
				});
		return map;
	}



}
